import { computed, onMounted, onUnmounted, ref } from 'vue';
import { storeToRefs } from 'pinia';

import pinia from "@/store";
import { User } from '@/store/user';
import { Wallet } from '@/store/wallet';
import { watch } from 'vue';
import { useI18n } from "vue-i18n";
import { showNotify } from "@nutui/nutui";
import { NetPacket } from '@/netBase/NetPacket';
import PKwebsocket from "@/lolo/Ws";
import { Local } from '@/utils/storage';
import {removeComma, verifyNumberComma} from "@/utils/publicMethods.ts";
import eventBus from '@/lolo/eventBus';

const useWalletInfo = () => {

  const calibrationRef = ref() // 提款校验-
  const withdrawMoneyRef = ref() // 提款

  const { t } = useI18n();
  const wallet = Wallet(pinia);
  const UserStore = User(pinia);
  const { info: userInfo, roleInfo } = storeToRefs(UserStore);
  const { bankCardInfoList } = storeToRefs(User(pinia));
  const loading = ref<boolean>(false);
  const updateAuto = ref<boolean>(false);
  const timerRe = ref();
  const refreshFlag = ref(false); //刷新标记
  const gameMoney = ref<number>(Number(roleInfo.value.money)); // 我的钱包余额
  const bankMoney = ref<number>(Number(roleInfo.value.bank_money)); // 保险柜余额
  const tranType = ref('in'); // 转账类型 out, in
  const tranMoney: any = ref<any>(); // 转账金额
  const eyeOpen = ref(true); // 余额是否可见 默认可见
  const slideValue = ref(0);   // 范围滑块

  const chooseMoneyArr = [
    { label: '100,000', value: 100000 },
    { label: '200,000', value: 200000 },
    { label: '500,000', value: 500000 },
    { label: '1,000,000', value: 1000000 },
    { label: '10,000,000', value: 10000000 },
  ];
  const slideStr = ref<any>('0%');
  const myBankList = ref(); // 已绑定的银行列表

  // 获取已绑定的银行账号
  const getMyBankList = () => {
    const req = NetPacket.req_bank_card_info_list();
    PKwebsocket.instance.send(req, true)
  }

  const handleMyBankList = (res: any) => {
    console.log(userInfo.value, '--------', res)
    res.bank_card_info_list = res.bank_card_info_list.reverse(); // 反转，需要跟支付管理那里一致
    myBankList.value = res;
    console.log('=====', roleInfo.value)

    // 未绑定银行卡跳转到绑定银行卡
    if (!myBankList.value.bank_card_info_list || myBankList.value.bank_card_info_list.length == 0) {
      // router.push('/wallet/paymentManagement')
      calibrationRef.value?.openModal();
      return
    }
    // 未绑定手机号码
    if (!userInfo.value.mobile) {
      // router.push('/wallet/securitySettings?openDialogType=bindPhone')
      calibrationRef.value?.openModal();
      return
    }
    // 未绑定资金密码
    if (!roleInfo.value.withdraw_pwd) {
      // router.push('/wallet/securitySettings?openDialogType=bindPayPwd')
      calibrationRef.value?.openModal();
      return
    }
    withdrawMoneyRef.value?.openModal();
    // showWithdrawModal(true)

  }

  // 取款需要判断是否绑定银行卡，绑定手机号码，提现密码
  const goToWithdraw = () => {
    getMyBankList();
  }

  const handleSubmit = () => {
    const numMon = removeComma(tranMoney.value);
    if (!numMon || numMon === 0) {
      return showNotify.danger(t('transfer_page_inputAmount'))
    }
    // 转入
    if (tranType.value === 'in') {
      if (numMon > gameMoney.value) {
        return showNotify.danger(t('transfer_page_notEnough'))
      }
    } else {
      if (numMon > bankMoney.value) {
        return showNotify.danger(t('transfer_page_notEnough'))
      }
    }

    loading.value = true;
    // 转入
    if (tranType.value === 'in') {
      GameToCenter();
    } else { // 转出
      centerToGame();
    }
  };
  // 中心钱包转账到游戏钱包
  const centerToGame = () => {
    const req = NetPacket.req_bank_take();
    req.money = removeComma(tranMoney.value).toString();
    PKwebsocket.instance.send(req, true)
  }
  const handleCenterToGame = (res: any) => {
    setTimeout(() => {
      loading.value = false;
    }, 300)
    if (res.is_success === 1) {
      tranMoney.value = '' // 清空金额
      showNotify.success(t('proxy_page_caoZuo'))
    } else {
      showNotify.danger(t('proxy_page_caoZuoFail'))
    }
  }
  // 游戏钱包转账到中心钱包
  const GameToCenter = () => {
    const req = NetPacket.req_bank_save();
    req.money = removeComma(tranMoney.value).toString();
    PKwebsocket.instance.send(req, true)
  }
  const handleGameToCenter = (res: any) => {
    setTimeout(() => {
      loading.value = false;
    }, 300)
    if (res.is_success === 1) {
      tranMoney.value = '' // 清空金额
      showNotify.success(t('proxy_page_caoZuo'))
    } else {
      showNotify.danger(t('proxy_page_caoZuoFail'))
    }
  }
  // 自动跟随 1打开，0关闭，默认打开
  const handleAutoTrans = (res: any) => {
    console.log('-----是否自动跟随', res)
    updateAuto.value = res.auto_trans === 1
    loading.value = false;
  };

  const getCurrencyValue = (val: number | string | undefined | null) => {
    const currencyUnit = Local.get('currency') || 1;
    console.warn(currencyUnit)
    switch (currencyUnit) {
      case 1:
      default:
        return Number(val);
      case 2:
        return Math.floor(Number(val) / Number(userInfo.value.usdt_rate) * 100) / 100
    }
  };
  const handleCurrencyChange = (key: number) => {
    Local.set('currency', key);
    // currencyUnit.value = key;
    gameMoney.value = getCurrencyValue(Number(roleInfo.value.money));
    bankMoney.value = getCurrencyValue(Number(roleInfo.value.bank_money));
    // totalMoney.value = gameMoney.value + bankMoney.value;
    // totalMoneyTxt.value = totalMoney.value;
    // target.value.bet_money = getCurrencyValue(target_bet_money.value);
  };

  const showWithdrawModal = (v: boolean) => wallet.setShowWithdraw(v);

  const refreshWallet = () => {
    if (!refreshFlag.value) {
      clearTimeout(timerRe.value);
      refreshFlag.value = true;
      getNewMon();
      timerRe.value = setTimeout(() => {
        refreshFlag.value = false
      }, 1 * 1000)
    }
  }

  // 金额显示隐藏
  const changeEyeOpen = (value: boolean) => {
    eyeOpen.value = value;
  }

  const getNewMon = () => {
    const req = NetPacket.req_roleinfo_with_id();
    req.id = Number(roleInfo.value.id);
    PKwebsocket.instance.send(req, true)
  }

  const initReq = () => {
    const transReq = NetPacket.req_auto_trans();
    PKwebsocket.instance.send(transReq, true)
  };

  // 转账类型切换
  const changeTranType = (type: any) => {
    tranMoney.value = ''; // 重置为 0
    tranType.value = type;
  }
  // 选择全部金额
  const allTranferMon = () => {
    if (tranType.value === 'in') {
      tranMoney.value = verifyNumberComma(String(gameMoney.value))
    } else {
      tranMoney.value = verifyNumberComma(String(bankMoney.value))
    }
    countMonRate();
  }
  // 选择快捷金额
  const chooseFastMon = (e: any) => {
    let avMon = 0; // 可转换的最高金额
    if (tranType.value === 'in') {
      avMon = gameMoney.value
    } else {
      avMon = bankMoney.value
    }
    if (!tranMoney.value) {tranMoney.value = 0}
    const curTranMon = removeComma(tranMoney.value);
    // 最高金额不能超过可转换的金额
    if (curTranMon + e > avMon) {
      tranMoney.value = avMon
    } else {
      tranMoney.value = curTranMon + e;
    }
    tranMoney.value = verifyNumberComma(String(tranMoney.value))
    countMonRate();
  }
  // 金额拖动
  const formatTooltip = (value: any) => {
    if (tranType.value === 'in') {
      tranMoney.value = verifyNumberComma(String((gameMoney.value * value) / 100), false)
    } else {
      tranMoney.value = verifyNumberComma(String((bankMoney.value * value) / 100), false)
    }
    slideStr.value = `${value}%`
    return slideStr.value
  }

  const inputBlur = () => {
    tranMoney.value = verifyNumberComma(String(tranMoney.value))
  }
  // 输入或者点击计算拖动比例
  const countMonRate = () => {
    tranMoney.value = removeComma(tranMoney.value)
    if (tranType.value === 'in') {
      slideValue.value = gameMoney.value ? parseInt(String((tranMoney.value / gameMoney.value) * 100)) : 0
    } else {
      slideValue.value = bankMoney.value ? parseInt(String((tranMoney.value / bankMoney.value) * 100)) : 0
    }
    tranMoney.value = verifyNumberComma(String(tranMoney.value), false) // 取整
    slideValue.value = slideValue.value > 100 ? 100 : (isNaN(slideValue.value) ? 0 : slideValue.value);
  }
  // 是否可以进行拖动转账
  const canSlide = computed(() => {
    if (tranType.value === 'in') {
      return gameMoney.value > 0
    } else {
      return bankMoney.value > 0
    }
  })

  // 重置金额
  const resetTranMoney = () => {
    tranMoney.value = ''
  }
  // 滑动条处理
  watch(
    () => tranMoney.value,
    (n) => {
      if (!n) {
        countMonRate();
      }
    }
  );
  // 更新余额等
  watch(
      () => roleInfo.value,
      (n) => {
        if (n) {
          console.log('-----&&&', n)
          handleCurrencyChange(1); // 默认越南盾
        }
      }
  );
  watch(
      () => bankCardInfoList.value,
      (n) => {
        handleMyBankList(n)
        console.log('=提现列表=*', n)
      }
  );
  onMounted(() => {
    eventBus.on('msg_notify_auto_trans', handleAutoTrans)
    eventBus.on('msg_notify_bank_take_result', handleCenterToGame)
    eventBus.on('msg_notify_bank_save_result', handleGameToCenter)
    setTimeout(() => {
      getNewMon();
      initReq();
    }, 500);
  });
  onUnmounted(() => {
    eventBus.off('msg_notify_auto_trans', handleAutoTrans)
    eventBus.off('msg_notify_bank_take_result', handleCenterToGame)
    eventBus.off('msg_notify_bank_save_result', handleGameToCenter)
  });
  return {
    loading,
    gameMoney,
    bankMoney,
    eyeOpen,
    showWithdrawModal,
    userInfo,
    roleInfo,
    updateAuto,
    refreshWallet,
    refreshFlag,
    goToWithdraw,
    myBankList,
    tranType,
    changeTranType,
    tranMoney,
    chooseMoneyArr,
    allTranferMon,
    formatTooltip,
    handleSubmit,
    slideStr,
    chooseFastMon,
    calibrationRef,
    withdrawMoneyRef,
    changeEyeOpen,
    canSlide,
    resetTranMoney,
    slideValue,
    countMonRate,
    inputBlur,
  };
}

export default useWalletInfo;
